import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

import 'blue_logic.dart';

class BluePage extends StatelessWidget {
  const BluePage({super.key});

  @override
  Widget build(BuildContext context) {
    final logic = Get.put(BlueLogic());

    return Scaffold(
      appBar: AppBar(
        title: const Text('蓝牙设置'),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: () => Get.back(),
        ),
        actions: [
          Obx(() => IconButton(
            icon: Icon(logic.isScanning.value ? Icons.stop : Icons.refresh),
            onPressed: () {
              if (logic.isScanning.value) {
                logic.stopScan();
              } else {
                logic.startScan();
              }
            },
          )),
        ],
      ),
      body: Obx(() {
        if (logic.connectedDevice.value == null) {
          return _buildScanList(logic);
        } else {
          return _buildDeviceControl(logic);
        }
      }),
    );
  }

  Widget _buildScanList(BlueLogic logic) {
    return ListView.builder(
      itemCount: logic.scanResults.length,
      itemBuilder: (context, index) {
        final result = logic.scanResults[index];
        return ListTile(
          title: Text(result.device.name.isEmpty ? 
              '未知设备' : result.device.name),
          subtitle: Text(result.device.id.id),
          trailing: Text('${result.rssi} dBm'),
          onTap: () => logic.connectToDevice(result.device),
        );
      },
    );
  }

  Widget _buildDeviceControl(BlueLogic logic) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildDeviceInfo(logic),
          const Divider(),
          _buildVolumeControl(logic),
          const Divider(),
          _buildModeControl(logic),
          const Divider(),
          _buildFrequencyControl(logic),
          const Divider(),
          _buildActionButtons(logic),
        ],
      ),
    );
  }

  Widget _buildDeviceInfo(BlueLogic logic) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('设备名称: ${logic.connectedDevice.value?.name ?? "未知设备"}'),
            const SizedBox(height: 8),
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('左耳: ${logic.leftEarConnected.value ? "已连接" : "未连接"}'),
                      Text('电量: ${logic.leftEarBattery.value}%'),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('右耳: ${logic.rightEarConnected.value ? "已连接" : "未连接"}'),
                      Text('电量: ${logic.rightEarBattery.value}%'),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildVolumeControl(BlueLogic logic) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('音量控制', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: Column(
                    children: [
                      const Text('左耳音量'),
                      Slider(
                        value: logic.leftEarVolume.value.toDouble(),
                        min: 1,
                        max: 5,
                        divisions: 4,
                        label: logic.leftEarVolume.value.toString(),
                        onChanged: (value) => logic.setVolume(0x01, value.toInt()),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    children: [
                      const Text('右耳音量'),
                      Slider(
                        value: logic.rightEarVolume.value.toDouble(),
                        min: 1,
                        max: 5,
                        divisions: 4,
                        label: logic.rightEarVolume.value.toString(),
                        onChanged: (value) => logic.setVolume(0x02, value.toInt()),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildModeControl(BlueLogic logic) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('工作模式', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 16),
            Wrap(
              spacing: 8,
              children: [
                ChoiceChip(
                  label: const Text('强降噪'),
                  selected: logic.workMode.value == 1,
                  onSelected: (selected) {
                    if (selected) logic.setWorkMode(0x03, 1);
                  },
                ),
                ChoiceChip(
                  label: const Text('室内'),
                  selected: logic.workMode.value == 2,
                  onSelected: (selected) {
                    if (selected) logic.setWorkMode(0x03, 2);
                  },
                ),
                ChoiceChip(
                  label: const Text('室外'),
                  selected: logic.workMode.value == 3,
                  onSelected: (selected) {
                    if (selected) logic.setWorkMode(0x03, 3);
                  },
                ),
                ChoiceChip(
                  label: const Text('自定义'),
                  selected: logic.workMode.value == 4,
                  onSelected: (selected) {
                    if (selected) logic.setWorkMode(0x03, 4);
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildFrequencyControl(BlueLogic logic) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('频率增益调节', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
            const SizedBox(height: 16),
            _buildFrequencySlider(logic, '500Hz', 0x80, logic.freq500Hz),
            _buildFrequencySlider(logic, '1kHz', 0x81, logic.freq1kHz),
            _buildFrequencySlider(logic, '2kHz', 0x82, logic.freq2kHz),
            _buildFrequencySlider(logic, '3kHz', 0x83, logic.freq3kHz),
            _buildFrequencySlider(logic, '4kHz', 0x84, logic.freq4kHz),
          ],
        ),
      ),
    );
  }

  Widget _buildFrequencySlider(BlueLogic logic, String label, int freqType, RxInt value) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label),
        Row(
          children: [
            const Text('-12'),
            Expanded(
              child: Slider(
                value: value.value.toDouble(),
                min: -12,
                max: 12,
                divisions: 24,
                label: value.value.toString(),
                onChanged: (v) => logic.setFrequencyGain(0x03, freqType, v.toInt()),
              ),
            ),
            const Text('+12'),
          ],
        ),
      ],
    );
  }

  Widget _buildActionButtons(BlueLogic logic) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        ElevatedButton(
          onPressed: () => logic.resetDevice(),
          style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
          child: const Text('恢复出厂设置'),
        ),
        ElevatedButton(
          onPressed: () => logic.disconnectDevice(),
          child: const Text('断开连接'),
        ),
        ElevatedButton(
          onPressed: () => logic.getStatus(),
          child: const Text('刷新状态'),
        ),
      ],
    );
  }
}